<?php

namespace app\admin\controller\wanlshop;

use app\common\controller\Backend;
use app\common\model\Distribution;
use think\exception\DbException;
use think\response\Json;

/**
 * 分佣订单管理
 *
 * @icon fa fa-circle-o
 */
class Indent extends Backend
{

    /**
     * 模型对象
     * @var \app\common\model\team\Level
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\Order();
        $this->view->assign("stateList", $this->model->getStateList());
        $this->view->assign("statusList", $this->model->getStatusList());

    }


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['user','shop','ordergoods',"distribution"=>function($query){
                    $query->where(["type"=>2]);
                }])
                ->join("(select DISTINCT order_id from fhb_distribution where type=2) a","a.order_id=order.id")
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['user','shop','ordergoods',"distribution"=>function($query){
                    $query->where(["type"=>2]);
                }])
                ->join("(select DISTINCT order_id from fhb_distribution where type=2) a","a.order_id=order.id")
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['username','nickname']);
                $row->getRelation('shop')->visible(['shopname']);
                //lina 修改 start
                if($row["type"]==1){
                    $row->pay=[
                        "price"=>0,
                        "order_price"=>0,
                        "freight_price"=>0,
                        "discount_price"=>0,
                        "actual_payment"=>0,
                    ];
                }else{
                    $row->pay = model('app\admin\model\wanlshop\Pay')
                        ->where(['order_id' => $row['id'], 'type' => 'goods'])
                        ->field('pay_no, price, order_price, freight_price, discount_price, actual_payment')
                        ->find();
                }
                //lina 修改 end
                //状态:0=待结算 1已结算 2已退款
                /*$row["distribution"]["status_text"]="待结算";
                if($row["distribution"]["status"]==1){
                    $row["distribution"]["status_text"]="已结算";
                }
                if($row["distribution"]["status"]==2){
                    $row["distribution"]["status_text"]="已退款";
                }*/
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $row['address'] = model('app\api\model\wanlshop\OrderAddress')
            ->where(['order_id' => $id])
            ->order('isaddress desc')
            ->field('id,name,mobile,address,address_name')
            ->find();

        //lina 修改 start
        /*$row['pay'] = model('app\admin\model\wanlshop\Pay')
            ->where(['order_id' => $row['id'], 'type' => 'goods'])
            ->find();*/
        if($row["type"]==1){
            $row['pay']=[
                "price"=>0,
                "order_price"=>0,
                "freight_price"=>0,
                "discount_price"=>0,
                "actual_payment"=>0,
                "pay_type"=>0,
                "pay_type_text"=>"——",
            ];
        }else{
            $row['pay'] = model('app\admin\model\wanlshop\Pay')
                ->where(['order_id' => $row['id'], 'type' => 'goods'])
                ->find();
        }
        //lina 修改 end
        // 查询快递状态
        switch ($row['state']) {
            case 1:
                $express = [
                    'context' => '付款后，即可将宝贝发出',
                    'status' => '尚未付款',
                    'time' => date('Y-m-d H:i:s', $row['createtime'])
                ];
                break;
            case 2:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已付款',
                    'time' => date('Y-m-d H:i:s', $row['paymenttime'])
                ];
                break;
            default: // 获取物流
                $eData = model('app\api\model\wanlshop\KuaidiSub')
                    ->where(['express_no' => $row['express_no']])
                    ->find();
                // 获取数据 兼容PHP7.4	1.1.5升级
                if(!empty($eData['data'])){
                    $ybData = json_decode($eData['data'], true);
                    // 运单状态 1.0.6升级
                    $statusText = ['在途','揽收','疑难','签收','退签','派件','退回','转投'];
                    $status = $statusText[0];
                    if(in_array('status', $ybData[0])){
                        $status = $ybData[0]['status'];
                    }else{
                        if($eData['ischeck'] === 1){
                            $status = $statusText[3];
                        }else{
                            $status = $statusText[$eData['state']];
                        }
                    }
                    $express = [
                        'status' => $status,
                        'context' => $ybData[0]['context'],
                        'time' => $ybData[0]['time'],
                    ];
                }else{
                    $express = [
                        'status' => '已发货',
                        'context' => '包裹正在等待快递小哥揽收~',
                        'time' => date('Y-m-d H:i:s', $row['delivertime'])
                    ];
                }
        }
        $row["distribution"]=Distribution::where(["order_id"=>$row["id"],"type"=>2])->with("commissuser")->select();
        $this->view->assign("kuaidi", $express);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
